package com.example.demo1.generator.codedesign;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.*;

public class JdbcUtil {

	private static final Logger logger = LoggerFactory.getLogger(JdbcUtil.class);

	public static ResultSet executeQuery(String sql, Connection conn, Object... params) {
		ResultSet rs = null;
		PreparedStatement statement = null;
		try {
			statement = conn.prepareStatement(sql);
			if(params != null){
				for (int i = 0; i < params.length; i++) {
					statement.setObject((i + 1), params[i]);
				}
			}
			rs = statement.executeQuery();
		} catch (SQLException e) {
			logger.error(e.getMessage(), e);
		}
		return rs;
	}

	public static void close(ResultSet rs) {
		if (rs != null) {
			try {
				Statement statement = rs.getStatement();
				if (!rs.isClosed()) {
					rs.close();
				}
				close(statement);
			} catch (SQLException e) {
				logger.error(e.getMessage(), e);
			}
		}
	}

	public static void close(Connection conn) {
		if (conn != null) {
			try {
				if (!conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				logger.error(e.getMessage(), e);
			}
		}
	}

	public static void close(Statement statement) {
		if (statement != null) {
			try {
				if (!statement.isClosed()) {
					statement.close();
				}
			} catch (SQLException e) {
				logger.error(e.getMessage(), e);
			}
		}
	}
}
